package com.example.myproject.jackson;

import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import com.fasterxml.jackson.databind.util.AccessPattern;

/**
 * Created by xi on 2018/9/21.
 */
public abstract  class NewPrimitiveOrWrapperDeserializer<T> extends StdScalarDeserializer<T> {

    private static final long serialVersionUID = 1L;

    protected final T _nullValue;

    // @since 2.9
    protected final T _emptyValue;

    protected final boolean _primitive;

    protected NewPrimitiveOrWrapperDeserializer(Class<T> vc, T nvl, T empty) {
        super(vc);
        _nullValue = nvl;
        _emptyValue = empty;
        _primitive = vc.isPrimitive();
    }

    @Override
    public AccessPattern getNullAccessPattern() {
        // 02-Feb-2017, tatu: For primitives we must dynamically check (and possibly throw
        //     exception); for wrappers not.
        if (_primitive) {
            return AccessPattern.DYNAMIC;
        }
        if (_nullValue == null) {
            return AccessPattern.ALWAYS_NULL;
        }
        return AccessPattern.CONSTANT;
    }

    @Override
    public final T getNullValue(DeserializationContext ctxt) throws JsonMappingException {
        // 01-Mar-2017, tatu: Alas, not all paths lead to `_coerceNull()`, as `SettableBeanProperty`
        //    short-circuits `null` handling. Hence need this check as well.
        if (_primitive && ctxt.isEnabled(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)) {
            ctxt.reportInputMismatch(this,
                    "Cannot map `null` into type %s (set DeserializationConfig.DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES to 'false' to allow)",
                    handledType().toString());
        }
        return _nullValue;
    }

}
